home *** CD-ROM | disk | FTP | other *** search
- LISTING 11 - Throws an exception in a constructor
-
- // destroy7.cpp
- #include <stdio.h>
-
- class Open_err
- {};
-
- class File
- {
- FILE *f;
- public:
- File(const char* fname, const char* mode)
- {
- f = fopen(fname, mode);
- if (f == NULL)
- throw Open_err();
- }
- ~File()
- {
- fclose(f);
- puts("File closed");
- }
- };
-
- void f(char *fname);
-
- main()
- {
- try
- {
- f("file1.dat");
- }
- catch(Open_err)
- {
- puts("File open error");
- }
- catch(...)
- {
- puts("Exception caught in main()");
- }
- return 0;
- }
-
- void f(char *fname)
- {
- File x(fname,"r");
- throw 1;
- }
-
- /* Output:
- File closed
- Exception caught in main()
- */
-
-